package com.cyanite.playlv2;

import com.cyanite.playlv2.widget.SecretFriendListAdapter;
import com.cyanite.playlv2api.types.Group;
import com.cyanite.playlv2api.types.User;
import com.cyanite.playlv2api.util.ConstantsUtils.ShareSecretLevelConsts;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;

import java.util.HashMap;
import java.util.LinkedHashMap;

public class SecretFriendsDialog extends Dialog {

    private PlayLv2 mPlaylv2;
    private Context mContext;
    private StateHolder mStateHolder;
    private SecretFriendListAdapter mListAdapter;
    private View mViewProgressBar;
    private EditText mNameFilter;
    private ListView mListView;
    private CheckBox mRight;
    private Handler mHandler;
    private RelativeLayout mHead;
    private UserChoosedStatusHandler mUserChoosedStatusHandler;
    private Button mButtonOk;
    private LinearLayout mEmpty;

    public SecretFriendsDialog(Context context, PlayLv2 playlv2,UserChoosedStatusHandler handler) {
        super(context);
        mContext = context;
        mPlaylv2 = playlv2;
        mUserChoosedStatusHandler = handler;
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.secret_friends_dialog);
        setTitle(mContext.getString(R.string.secret_set_friends_right));

        mStateHolder = new StateHolder();
        mStateHolder.setUserId(mPlaylv2.getUserId());

        mViewProgressBar = findViewById(R.id.llSecretProgress);
        mViewProgressBar.setVisibility(View.VISIBLE);
        mStateHolder.startTaskFriendOnPlayLv2(this,mPlaylv2);
        ensureUi();
    }

    private void ensureUi(){
        mHandler = new Handler();
        mEmpty = (LinearLayout)findViewById(R.id.llEmptySecretFriends);
        mNameFilter = (EditText)findViewById(R.id.etTextFilter);
        mNameFilter.addTextChangedListener(new TextWatcher() {
            public void afterTextChanged(Editable s) {
            }
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mHandler.removeCallbacks(mRunnableFilter);
                mHandler.postDelayed(mRunnableFilter, 700L);
            }
        });
        mListView = (ListView)findViewById(R.id.lvSecretFriends);
        mHead = (RelativeLayout)findViewById(R.id.rlHead);
        mRight = (CheckBox)findViewById(R.id.cbAllFriends);
        mRight.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked == true){
                    mListAdapter.setIsAllFriends(isChecked);
                    mListAdapter.notifyDataSetChanged();
                }
            }
        });

        mButtonOk = (Button)findViewById(R.id.btnSecretOk);
        mButtonOk.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                int secretLevel;
                if(mRight.isChecked()){
                    secretLevel = ShareSecretLevelConsts.SHARE_SECRET_LEVEL_FRIEND;
                }else{
                    secretLevel = ShareSecretLevelConsts.SHARE_SECRET_LEVEL_SECRET;

                }
                String userIds = null;
                if(mRight.isChecked() == false){
                    userIds = mListAdapter.getUsersIdString();
                }
                mUserChoosedStatusHandler.onUsersChoosed(secretLevel, userIds);
                dismiss();
            }
        });
    }
    
    private void infoFriendOnPlaylv2(User user) {
        Intent intent = new Intent(mContext, UserDetailsActivity.class);
        intent.putExtra(UserDetailsActivity.EXTRA_USER_PARCEL, user);
        mContext.startActivity(intent);
    }
    private SecretFriendListAdapter.ButtonRowClickHandler mButtonRowClickHandler =
        new SecretFriendListAdapter.ButtonRowClickHandler() {
            @Override
            public void onClickInfo(User user) {
                infoFriendOnPlaylv2(user);
            }

            @Override
            public void onCheckButtonClick(boolean isTrue) {
                if(isTrue == false){
                    if(mRight.isChecked() == true){
                        mRight.setChecked(false);
                    }

                }
            }
    };
    
    private Runnable mRunnableFilter = new Runnable() {
        public void run() {
            mStateHolder.filterFriendRequests(mNameFilter.getText().toString());
            mListAdapter.setGroup(mStateHolder.getFoundFriendsFiltered());
            mListAdapter.notifyDataSetChanged();
        }
    };
    
    private void onFriendsOnPlayLv2TaskComplete(Group<User> users, HashMap<String, Group<User>> usersAlpha, Exception ex) {
        mViewProgressBar.setVisibility(View.GONE);
        // Recreate the adapter, cleanup beforehand.
        if(mListAdapter != null){
            mListAdapter.removeObserver();
        }
        if (users != null) {
            mHead.setVisibility(View.VISIBLE);
            mButtonOk.setVisibility(View.VISIBLE);
            mListAdapter = new SecretFriendListAdapter(mContext,mPlaylv2.getRemoteResourceManager(),mButtonRowClickHandler);
            mStateHolder.setFriends(users, usersAlpha);
            mListAdapter.setGroup(mStateHolder.getFoundFriendsFiltered());
            mListView.setAdapter(mListAdapter);
        }else{
            mEmpty.setVisibility(View.VISIBLE);
        }
    }

    private static class FriendsOnPlayLv2Task extends AsyncTask<String, Void, Group<User>> {

        private SecretFriendsDialog  mDialog;
        private HashMap<String, Group<User>> mRequestsAlpha;
        private Exception mReason;
        private PlayLv2 mPlaylv2;

        public FriendsOnPlayLv2Task(SecretFriendsDialog dialog, PlayLv2 playlv2) {
            mDialog = dialog;
            mPlaylv2 = playlv2;
            mRequestsAlpha = new LinkedHashMap<String, Group<User>>();
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected Group<User> doInBackground(String... params) {
            try {
                Group<User> requests =  mPlaylv2.getPlayLv2Api().friends(params[0]);
                if (requests != null && !requests.isEmpty())   {
                    for (User it : requests) {
                        String name = it.getUserName();
                        String first = name.substring(0, 1);
                        Group<User> block = mRequestsAlpha.get(first);
                        if (block == null) {
                            block = new Group<User>();
                            mRequestsAlpha.put(first, block);
                        }
                        block.add(it);
                    }
                }
                return requests;
            } catch (Exception ex) {
                mReason = ex;
                return null;
            }
        }

        @Override
        protected void onPostExecute(Group<User> users) {
            if (mDialog != null) {
                mDialog.onFriendsOnPlayLv2TaskComplete(users, mRequestsAlpha, mReason);
            }
        }
    }

    private static class StateHolder {
        private Group<User> mFriends;
        private Group<User> mFoundFriendsFiltered;
        private FriendsOnPlayLv2Task mTaskFriendsOnPlayLv2;
        private String mUserId;

        public StateHolder() {
            mTaskFriendsOnPlayLv2 = null;

        }

        public void setUserId(String userId)    {
            mUserId = userId;
        }
        
        public void startTaskFriendOnPlayLv2(SecretFriendsDialog dialog, PlayLv2 playlv2) {
            mTaskFriendsOnPlayLv2 = new FriendsOnPlayLv2Task(dialog,playlv2);
            mTaskFriendsOnPlayLv2.execute(mUserId);
        }

        public Group<User> getFoundFriendsFiltered() {
            if (mFoundFriendsFiltered == null) {
                return mFriends;
            }
            return mFoundFriendsFiltered;
        }

        public void setFriends(Group<User> requests, HashMap<String, Group<User>> alpha) {
            if (requests != null) {
                mFriends = requests;
                mFoundFriendsFiltered = null;
            } else {
                mFriends = new Group<User>();
                mFoundFriendsFiltered = null;
            }
        }

        public void filterFriendRequests(String filterString) {
            // If no filter, just keep using the original found friends group.
            // If a filter is supplied, reconstruct the group using the alpha
            // map so we don't have to go through the entire list.
            mFoundFriendsFiltered = null;
            if (!TextUtils.isEmpty(filterString)) {

                mFoundFriendsFiltered = new Group<User>();
                if (mFriends != null) {
                    for (User it : mFriends) {
                        String name = it.getUserName();
                        if (name.startsWith(filterString)) {
                            mFoundFriendsFiltered.add(it);
                        }
                    }
                }
            }
        }
    }
    
    public interface UserChoosedStatusHandler {
        public void onUsersChoosed(int secretLevel,String usersIdString);
    }
}
